import { clear_gun, get_gun } from 'base/api';
import { s_psn, g_db } from 'db/state';
import { put_log } from 'base/ctl/log';
import { msn_info, is_new } from 'use/info';
import { insert_box, calc_pos } from './cmd';
import { is_range } from '../client/away/data/base';
import { uJob, uDb, cline, urlTb, obj_str, obj_float } from 'sui';

const ck_range = (opt, r) => {
    const dt = obj_float(r, "dt");
    if (!is_range(opt, "dt_min", "dt_max", dt)) {
        return `沟径数据不在范围之内: ${dt}`;
    }

    const dia = obj_float(r, "dia");
    if (!is_range(opt, "dia_min", "dia_max", dia)) {
        return `直径数据不在范围之内: ${dia}`;
    }

    const width = obj_float(r, "width");
    if (!is_range(opt, "w_min", "w_max", width)) {
        return `直径数据不在范围之内: ${width}`;
    }

    return null;
};

const add_pick = (psn, tsn, dia, dt, width, hok, herr) => {
    const tp = g_db.boxtp();

    if (!tp) {
        return herr("箱子类型错误");
    }

    const opt = {
        dia_min: g_db.dia_min(),
        dia_max: g_db.dia_max(),
        dt_min: g_db.dt_min(),
        dt_max: g_db.dt_max(),
        w_min: g_db.w_min(),
        w_max: g_db.w_max(),
    };

    const v = {
        dia: dia * 1000,
        dt: dt * 1000,
        width: width * 1000,
    }

    const e = ck_range(opt, v);
    if (e) {
        return herr(e);
    }

    uDb(null, "tech/get",
        {
            line: cline(),
            k: tsn,
        },
        r => {
            const val = {
                line: cline(),
                data: [{
                    psn: psn,
                    wsn: "auto",
                    k: {
                        usn: "auto",
                        tsn: tsn,
                    },
                    v: {
                        state: 1,
                    }
                }]
            };

            put_log("add pick", tp, "箱子类型");

            if (tp === "inner") {
                put_log("add pick", "", "保存内圈");

                const b_dia = obj_float(r, "india");
                const b_dt = obj_float(r, "indt");
                const b_width = obj_float(r, "inwidth");

                val["tab"] = "india";
                val["data"][0]["v"]["val"] = dia + b_dia;
                urlTb(null, "chunk", val);

                val["tab"] = "indt";
                val["data"][0]["v"]["val"] = dt + b_dt;
                urlTb(null, "chunk", val);

                val["tab"] = "inwidth";
                val["data"][0]["v"]["val"] = width + b_width;
                urlTb(null, "chunk", val);
            } else if (tp === "outer") {
                put_log("add pick", "", "保存外圈");

                const b_dia = obj_float(r, "outdia");
                const b_dt = obj_float(r, "outdt");
                const b_width = obj_float(r, "outwidth");

                val["tab"] = "outdia";
                val["data"][0]["v"]["val"] = dia + b_dia;
                urlTb(null, "chunk", val);

                val["tab"] = "outdt";
                val["data"][0]["v"]["val"] = dt + b_dt;
                urlTb(null, "chunk", val);

                val["tab"] = "outwidth";
                val["data"][0]["v"]["val"] = width + b_width;
                urlTb(null, "chunk", val);
            }

            hok();
        },
        e => herr(`工艺号 ${tsn} 不存在`));
};

const ck_split = (psn, hok, herr) => {
    const tp = g_db.boxtp();

    if (!tp) {
        return herr("箱子类型错误");
    }

    let tab = "outer";
    let pre = "out";

    if (tp === "inner") {
        tab = "inner";
        pre = "in";
    }

    const cmd = {
        n: tab,
        db: "old",
        obj: "*",
        opt: {
            desc: true,
            limit: 1,
            and: [
                {eq: "line", v: cline()},
                {eq: "psn", v: psn},
            ]
        }
    };

    urlTb(null, "get", cmd,
        r => {
            const val = r[tab]["data"];
            if (!val) {
                return herr(`没有找到数据`);
            }

            const v = val[0];

            put_log(tab, psn, v);

            let tsn = obj_str(v, "tsn");

            if (tsn.endsWith("W")) {
                if (tsn !== "7006-36KHNW" && tsn !== "7014-14KHNW") {
                    tsn = tsn.slice(0, -1);
                }
            }

            const tmp = tsn.split("-");
            if (tmp[0].startsWith("70020")) {
                tmp[0] = "7020";
                tsn = tmp.join("-");
            }

            let dia = obj_str(v, `${pre}dia`);
            if (!dia) {
                return herr(`直径为不存在`);
            }

            let dt = obj_str(v, `${pre}dt`);
            if (!dt) {
                return herr(`沟径为不存在`);
            }

            let width = obj_str(v, `${pre}width`);
            if (!width) {
                return herr(`宽度不存在`);
            }

            dia = obj_float(v, `${pre}dia`);
            dt = obj_float(v, `${pre}dt`);
            width = obj_float(v, `${pre}width`);

            const df = `${psn[6]}${psn[4]}${psn[2]}`;

            if (tp === "inner") {
                if (tsn.startsWith("7014-10")) {
                    if (df <= "LAF") {
                        dia += 2;
                    }
                } else if (tsn.startsWith("7014-15")) {
                    if (df <= "LAM") {
                        dia += 2;
                    }
                } else if (tsn.startsWith("7016")) {
                    if (df <= "LAN") {
                        dia += 2;
                    }
                } else if (tsn.startsWith("7018")) {
                    if (df <= "LC9") {
                        dia += 1;
                    }
                } else if (tsn.startsWith("7020")) {
                    if (df <= "LA9") {
                        dia += 2;
                    }
                }
            }

            add_pick(psn, tsn, dia / 1000, dt / 1000, width / 1000, hok, herr);
        },
        e => herr("没有找到数据"));
};

const do_oldpick = (stepnum, step, umd, watch) => {
    const psn = get_gun(step);
    if (!psn) {
        watch.startWatch();
        return;
    }

    put_log("编码", psn, "扫描轴承编码");

    clear_gun();
    s_psn(psn);

    umd.set("psn", psn);

    const herr = (e) => {
        umd.setErr(e);
        watch.startWatch();
    };

    if (psn.length < 8) {
        return herr("条码位数错误");
    }

    if (psn.length > 10) {
        return herr("条码位数错误");
    }

    const v_tray = g_db.boxtray();
    const v_level = g_db.boxlv();

    if (!v_tray || !v_level) {
        return herr("请先设置托盘规格和层数");
    }

    if (!is_new(psn)) {
        return herr("条码已经入箱");
    }

    const sum = g_db.sum() + 1;

    if (sum > v_tray * v_level) {
        return herr("已经达到最大装箱容量");
    }

    const pos = calc_pos(sum);

    ck_split(psn, () => {
        insert_box(g_db.box(), psn, pos, () => {
            const cmd = {
                line: cline(),
                tp: g_db.boxtp(),
                box: g_db.box(),
                sn: psn,
            };

            uJob(null, "pick/add", cmd);

            msn_info(psn, pos);

            let num = g_db.num() + 1;

            g_db.s_num(num);
            g_db.s_sum(sum);

            umd.mset({
                sum: sum,
                num: num,
                err: "",
            });

            watch.startWatch();
        }, e => {
            umd.setErr("入箱出错, 请重新扫码");
            watch.startWatch();
        });
    }, e => herr(e));
};

export {do_oldpick};
